import { Instance } from "../instance";
import readline from "readline";

export class ReadlineUtils {
  private static READ_LINE_NAME = "ys.utils.read";

  /**
   * 阻塞读取一行数据
   * 当没有 readline 实例时创建一个新的
   * @param msg 需要显示信息
   */
  public static ysReadline = (msg: string) => {
    let rd = Instance.Instance().get<readline.ReadLine>(this.READ_LINE_NAME);
    if (rd === null) {
      rd = readline.createInterface(process.stdin, process.stdout);
      Instance.Instance().set(this.READ_LINE_NAME, rd);
    }

    return new Promise((resolve) => {
      rd!.question(msg, (line: string) => {
        resolve(line);
      });
    });
  };

  /**
   * 关闭自动创建的 readline 实例
   */
  public static ysReadlineClose = () => {
    const rd = Instance.Instance().get<readline.ReadLine>(this.READ_LINE_NAME);
    if (rd) {
      rd.close();
      Instance.Instance().remove(this.READ_LINE_NAME);
    }
  };
}
